<template>
    <div>
        <div class="goods-toolbar">
            <div class="goods-navbar">首页
                <span class="goods-navbar-arrow">></span>
                <span>{{currentClassify.name}}</span>
                <template v-if="$route.query.keyword">
                    <span class="goods-navbar-arrow">></span>
                    <span>{{$route.query.keyword}}</span>
                </template>
            </div>
            <div v-if="goods.length>0" class="goods-total-count">共 {{goodsLength}} 件商品</div>
            <div v-else class="goods-total-count">抱歉，没有找到商品。</div>
            <div class="goods-navbar-filter">
                <div class="goods-navbar-filter-item" v-for="item in filter">
                    <span v-if="item.type==1">品牌：</span>
                    <span v-if="item.type==2">分类：</span>
                    <span v-if="item.type==3">关键字：</span>
                    <div class="goods-navbar-filter-item-value">{{item.name}}</div>
                    <a href="javascript:void(0);" @click="deleteFilter(item)">&times;</a>
                </div>
                <div v-if="hasResultKeyword" class="goods-navbar-filter-item">
                    <input class="form-control" type="text" placeholder="在结果中搜索" v-model="searchKey" @keyup.enter="search" />
                    <el-button size="small" @click="search">确定</el-button>
                </div>
            </div>
        </div>
        <div class="clear"></div>
        <div v-if="filterBrands.length>0&&!$route.query.brands" class="filter" :style="showDetail?'padding:0;':''">
            <div v-if="!isMulti" class="brands-filter-expand">
                <el-button v-if="brandFilter.length>10" size="mini" :icon="showDetail?'arrow-up':'arrow-down'" @click="more">更多</el-button>
                <el-button v-if="brandFilter.length>1" size="mini" icon="plus" @click="multiSelect">多选</el-button>
            </div>
            <template v-if="!showDetail">
                <div class="filter__title">
                    <p>品牌</p>
                </div>
                <div class="filter__list">
                    <a v-for="item in filterBrands" class="filter__list__item" @click="handleSelectBrand(item.brandInfo.id)">{{item.brandInfo.name}}</a>
                </div>
            </template>
            <template v-else>
                <div class="brand-filter-detail" :class="isMulti?'multi-detail':''">
                    <div class="brand-row-title">
                        <p>品牌</p>
                    </div>
                    <div class="brand-row-filter">
                        <first-Letter-filter :letters='letters' v-on:firstLetterSelect="firstLetterSelect">
                            <input slot="input" class="form-control" type="text" placeholder="可输入拼音、汉字查找品牌" v-model="brandSearchfilter.name" v-on:keyup="doFilter">
                        </first-Letter-filter>
                        <div class="brand-item">
                            <div v-for="item in brandFilter">
                                <label v-if="isMulti" :for="'checkbox'+item.brandInfo.id">
                                    <input type="checkbox" :id="'checkbox'+item.brandInfo.id" :value="item" v-model="brandSelectData">
                                    <span>{{item.brandInfo.name}}</span>
                                </label>
                                <label v-else>
                                    <span class="single-select" @click="handleSelectBrand(item.brandInfo.id)">{{item.brandInfo.name}}</span>
                                </label>
                            </div>
                        </div>
                        <div v-if="brandSelectData.length > 0">
                            <div class="brand-row-title-select">
                                <p>已选条件</p>
                            </div>
                            <div class="brand-row-filter-select">
                                <div class="brand-select-result">
                                    <div class="brand-select-node" v-for="(item,index) in brandSelectData">
                                        <label :for="'checkbox'+item.brandInfo.id">
                                            <input type="checkbox" :id="'checkbox'+item.brandInfo.id" :value="item" v-model="brandSelectData">
                                            <span>{{item.brandInfo.name}}</span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-if="isMulti" class="brand-filter-btn-group">
                        <el-button type="primary" size="small" @click="multiSelectBrand">确认</el-button>
                        <el-button size="small" @click="showDetail = false;isMulti=false;">取消</el-button>
                    </div>
                </div>
            </template>
        </div>
        <div v-if="$route.query.main_category&&filterCategorys.length>0&&!$route.query.categories" class="filter">
            <div class="filter__title">
                <p>{{currentClassify.name}}</p>
            </div>
            <div class="filter__list">
                <a v-for="item in filterCategorys" v-if="item.categoryInfo.grade !== 1" class="filter__list__item" @click="handleSelectCategory(item.categoryInfo.id )">{{item.categoryInfo.name}}</a>
            </div>
        </div>
        <div class="goods-list">
            <div v-if="goods.length>0">
                <table>
                    <tbody>
                        <tr v-for="(item,index) in goods">
                            <td width="1%">
                                <a :href="'/'+$store.state.domain+'/goods/detail?id='+item.id" target="_blank">
                                    <img v-if="item.spu.resources.length" :src="item.spu.resources[0].url" alt="" width="80px;">
                                    <img v-else src="~assets/images/default-pic.png" width="80px;">
                                </a>
                            </td>
                            <td width="30%">
                                <div class="good-list-name" :title="item.title">
                                    <a :href="'/'+$store.state.domain+'/goods/detail?id='+item.id" target="_blank">{{item.name}}</a>
                                </div>
                            </td>
                            <td width="20%">
                                <div :title="item.spu.brand.name+'/'+item.sn">
                                    <span style="color:#666;">品牌型号：</span>{{item.spu.brand.name}}/{{item.sn}}</div>
                            </td>
                            <td width="10%">
                                <div v-if="item.priceStatus===1">待报价</div>
                                <div v-else>¥ {{item.price}}</div>
                            </td>
                            <td width="1%">
                                <count-step v-model="counts[item.id]" :item-index="item.id" @stepChange="addOrMinus"></count-step>
                                <div v-if="showTips[item.id]" class="tip">
                                    <i class="el-icon-information"></i> 最小采购数量为1
                                </div>
                            </td>
                            <td width="1%">
                                <el-button type="primary" @click="addToCart(item)">加入货品清单</el-button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="good-list-loading" v-else>
                <img src="~assets/images/sorry_null.png" alt=""> 抱歉，没有搜索到您需要的商品
            </div>
        </div>
        <div class="goods-page" v-if="goods.length>0">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 40, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageLength">
            </el-pagination>
        </div>
    </div>
</template>

<script>

import { Button, Pagination, Notification } from 'element-ui'
import { mapState, mapMutations } from 'vuex'
import service from '../../../service/Service'
import WebStorage from '../../../service/WebStorage'
import FirstLetterFilter from '~components/FirstLetterFilter'
import CountStep from '~components/CountStep'

export default {
    layout: 'main',
    scrollToTop: true,
    components: {
        'el-button': Button,
        'el-pagination': Pagination,
        FirstLetterFilter,
        CountStep,
    },
    async asyncData (context) {
        const { query } = context
        let queryData = {}
        if (query.keyword) {
            queryData.keyword = query.keyword
        }
        // if (query.priceStatus) {
        //     queryData.priceStatus = query.priceStatus
        // }
        if (query.brands) {
            queryData.brands = query.brands.split('_')
        }
        if (query.main_category) {
            queryData.categories = [query.main_category]
        }
        if (query.categories) {
            queryData.categories = query.categories.split('_')
        }
        if (query.page) {
            queryData.page = query.page
        }
        if (query.page_size) {
            queryData.page_size = query.page_size
        }
        if (query.exp_key) {
            queryData.keyword = query.exp_key
        }
        let { data } = await service.getEsGoods({ page: queryData.page ? queryData.page : 1, perPage: queryData.page_size ? queryData.page_size : 20, ...queryData }, context)

        let letters = []
        for (let item of data.result.filterBrands) {
            if (letters.indexOf(item.brandInfo.firstLetter) === -1) {
                letters.push(item.brandInfo.firstLetter)
            }
            item.status = false
        }
        for (let item of data.result.filterCategories) {
            item.status = false
        }
        let counts = {}
        let showTips = {}
        for (let item of data.result.productPager.pageItems) {
            counts[item.id] = 1
            showTips[item.id] = false
        }

        let filter = []
        for (let prop in query) {
            if (prop === 'categories') {
                const { categoryInfo } = data.result.filterCategories.find(({ categoryInfo }) => {
                    if (categoryInfo.id + '' === query[prop] + '') {
                        return true
                    }
                })
                if (categoryInfo) {
                    filter.push({ type: 2, name: categoryInfo.name })
                }
            } else if (prop === 'brands') {
                let brandsSplit = query[prop].split('_')
                const existBrands = data.result.filterBrands.filter(({ brandInfo }) => {
                    if (brandsSplit.indexOf(brandInfo.id) !== -1) {
                        return true
                    }
                })
                if (existBrands) {
                    let name = []
                    for (let item of existBrands) {
                        name.push(item.brandInfo.name)
                    }
                    filter.push({ type: 1, name: name.join(',') })
                }
            } else if (prop === 'exp_key') {
                filter.push({ type: 3, name: query[prop] })
            }
        }
        let pageLength = data.result.productPager.rowsCount > 10000 ? 10000 : data.result.productPager.rowsCount
        return {
            goods: data.result.productPager.pageItems,
            goodsLength: data.result.productPager.rowsCount,
            pageLength,
            filterCategorys: data.result.filterCategories,
            filterBrands: data.result.filterBrands,
            brandFilter: data.result.filterBrands,
            query,
            counts,
            showTips,
            currentPage: queryData.page ? parseInt(queryData.page) : 1,
            pageSize: queryData.page_size ? parseInt(queryData.page_size) : 20,
            filter,
            letters,
        }
    },
    data () {
        return {
            searchKey: '',
            showDetail: false,
            isMulti: false,
            brandSearchfilter: {
                firstLetter: '',
                name: '',
            },
            brandSelectData: [],
        }
    },
    computed: {
        ...mapState(['currentClassify']),
        hasResultKeyword () {
            if (this.currentClassify.id !== -1) {
                for (let item of this.filter) {
                    if (item.type === 3) {
                        return false
                    }
                }
                return true
            }
            return false
        },
    },
    methods: {
        actionRoute (query) {
            query._ = new Date().getTime()
            this.$router.push({ name: 'domain-goods-listAll', query })
        },
        handleSizeChange (val) {
            this.actionRoute({ ...this.query, page_size: val })
        },
        handleCurrentChange (val) {
            this.actionRoute({ ...this.query, page: val })
        },
        handleSelectBrand (id) {
            this.actionRoute({ ...this.query, brands: id })
        },
        handleSelectCategory (id) {
            this.actionRoute({ ...this.query, categories: id })
        },
        search () {
            if (this.searchKey) {
                this.actionRoute({ ...this.query, exp_key: this.searchKey })
            }
        },
        ...mapMutations(['refreshCart']),
        deleteFilter (item) {
            switch (item.type) {
            case 1:
                delete this.query.brands
                this.actionRoute({ ...this.query })
                break
            case 2:
                delete this.query.categories
                this.actionRoute({ ...this.query })
                break
            case 3:
                delete this.query.exp_key
                this.actionRoute({ ...this.query })
                break
            default:
                break
            }
        },
        addOrMinus (value) {
            if (value.type === 'add') {
                this.counts[value.itemIndex] += 1
            } else {
                if (this.counts[value.itemIndex] > 1) {
                    this.counts[value.itemIndex] -= 1
                } else {
                    this.showTips[value.itemIndex] = true
                    setTimeout(() => {
                        this.showTips[value.itemIndex] = false
                    }, 2000)
                }
            }
        },
        addToCart (item) {
            var image = ''
            if (item.spu.resources && item.spu.resources.length > 0) {
                image = item.spu.resources[0].url
            }
            const { id, sn, price, priceStatus, name, spu } = item
            WebStorage.addToCart([{
                count: parseInt(this.counts[item.id]),
                image: image,
                item: {
                    id,
                    brand: spu.brand.name,
                    sn,
                    name,
                    priceStatus,
                    price,
                },
            }])
            this.counts[item.id] = 1
            Notification.success({
                message: '加入货品清单成功',
                offset: 90,
            })
            this.refreshCart()
        },
        firstLetterSelect (value) {
            this.brandSearchfilter.firstLetter = value
            this.doFilter()
        },
        doFilter () {
            var name = this.brandSearchfilter.name
            var firstLetter = this.brandSearchfilter.firstLetter
            this.brandFilter = this.filterBrands.filter(item => {
                if (!name || item.brandInfo.name.indexOf(name) !== -1 || item.brandInfo.nameEn.indexOf(name) !== -1) {
                    if (firstLetter === '-1') {
                        return true
                    }
                    if (item.brandInfo.firstLetter.toUpperCase() === firstLetter.toUpperCase()) {
                        return true
                    }
                }
                return false
            })
        },
        multiSelect () {
            this.showDetail = true
            this.isMulti = true
        },
        more () {
            if (this.showDetail) {
                this.showDetail = false
                this.isMulti = false
            } else {
                this.showDetail = true
                this.isMulti = false
                this.brandFilter = [...this.filterBrands]
            }
        },
        multiSelectBrand () {
            if (this.brandSelectData.length > 0) {
                var brands = []
                for (let item of this.brandSelectData) {
                    brands.push(item.brandInfo.id)
                }
                this.$router.push({ name: 'domain-goods-listAll', query: { ...this.query, brands: brands.join('_'), _: new Date().getTime() } })
            }
        },
    },
}
</script>

<style lang="scss" scoped>
.goods-toolbar {
    padding: 20px 15px;
    border-bottom: 1px solid #ddd;
    float: left;
    width: 100%;
    .goods-navbar {
        color: #333;
        line-height: 30px;
        float: left;
        .goods-navbar-arrow {
            margin: 0 10px;
        }
        span {
            color: #999;
        }
    }
    .goods-total-count {
        line-height: 30px;
        color: #999;
        float: right;
    }
    .good-list-type {
        li {
            a {
                font-size: 18px;
                color: #c7cace;
                padding-top: 14px;
                padding-bottom: 14px;
            }
        }
        li.active {
            a {
                color: #333;
            }
        }
    }
    .goods-navbar-filter {
        margin-left: 20px;
        float: left;
        .goods-navbar-filter-item {
            border: 1px solid #e7e7e7;
            line-height: 27px;
            height: 30px;
            padding-left: 8px;
            margin-right: 10px;
            float: left;
            font-size: 13px;
            div {
                height: 32px;
                vertical-align: middle;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                color: #999;
                display: inline-block;
                max-width: 120px;
            }
            .goods-navbar-filter-item-value {
                color: #337ab7;
            }
            a {
                text-decoration: none;
                margin-left: 10px;
                margin-right: 5px;
                font-size: 15px;
                color: #337ab7;
            }
            button {
                border-radius: 0;
                height: 30px;
                margin-top: -1px;
                margin-right: -1px;
                border-color: #e7e7e7;
                &:hover {
                    border-color: #20a0ff;
                }
            }
            input {
                font-size: 13px;
                border: none;
                box-shadow: none !important;
                padding: 0;
                height: 27px;
                display: inline-block;
                width: 100px;
                outline: none;
            }
        }
    }
}

.filter {
    border-bottom: 1px solid #ddd;
    min-height: 76px!important;
    overflow-y: hidden;
    padding: 20px 15px;
    line-height: 25px;
    position: relative;
    .filter__title {
        width: 120px;
        position: absolute;
        p {
            font-size: 14px;
            font-weight: bold;
        }
    }
    .filter__list {
        padding-left: 120px;
        padding-right: 130px;
        overflow-y: hidden;
        max-height: 50px;
        .filter__list__item {
            display: inline-block;
            cursor: pointer; // min-width: 120px;
            margin-right: 40px;
            font-size: 14px;
            color: #666;
        }
    }
    .brand-filter-detail {
        border-left: 1px solid #e7e7e7;
        border-right: 1px solid #e7e7e7;
        padding: 20px 14px;
        .brand-filter-btn-group {
            text-align: center;
            margin: 10px 0 20px;
            button {
                border-radius: 0!important;
            }
        }
    }
    .multi-detail {
        border-left: 3px solid #20a0ff;
        border-right: 3px solid #20a0ff;
        border-top: 2px solid #20a0ff;
        border-bottom: 2px solid #20a0ff;
    }
    .brands-filter-expand {
        position: absolute;
        right: 20px;
        top: 20px;
        button {
            color: #666;
            border-radius: 0;
        }
    }
    .brand-row-title {
        width: 90px;
        position: absolute;
        p {
            font-size: 14px;
            font-weight: bold;
        }
    }
    .brand-row-title-select {
        position: absolute;
        color: #777;
    }
    label {
        font-size: 13px;
    }
    input[type=checkbox]:checked+span {
        color: #337ab7;
    }
    .brand-row-filter-select {
        padding-left: 90px;
    }
    .brand-row-filter {
        padding-left: 120px;
        padding-right: 130px;
        .brand-item {
            margin-top: 15px;
            max-height: 144px;
            overflow-y: auto;
            line-height: initial;
            >div {
                display: inline-block;
                margin: 2px 0;
                height: 25px;
                line-height: 25px;
                input {
                    margin-right: 5px;
                }
                label {
                    display: inline-block;
                    max-width: 100%;
                    margin-bottom: 5px;
                    font-weight: normal;
                    width: 90px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    color: #777;
                }
            }
            .single-select {
                cursor: pointer;
                user-select: none;
                &:hover {
                    color: #00a2ff;
                }
            }
        }
        .brand-select-result {
            input {
                margin-right: 5px;
            }
            .brand-select-title {
                padding: 3px 10px;
                background-color: #eee;
                cursor: default;
                font-size: 13px;
                border: 1px solid #ddd;
            }
            .brand-select-delete {
                color: white;
                background-color: #337ab7;
                padding: 3px 7px;
                margin-left: -4px;
                text-decoration: none;
                &:hover {
                    background-color: #24547d;
                }
            }
            .brand-select-node {
                display: inline-block;
                color: #666;
                margin: 0 25px 10px 0;
            }
        }
    }
}

.goods-list {
    .good-list-loading {
        text-align: center;
        font-size: 18px;
        color: #999;
        margin-top: 60px;
        img {
            display: block;
            margin: 0 auto;
            margin-bottom: 30px;
        }
    }
    table {
        width: 100%;
        border-spacing: 0;
        border-collapse: collapse;
        box-sizing: border-box;
        tr {
            border-bottom: 1px solid #ddd;
            td {
                padding: 15px 20px;
                color: #666666;
                height: 115px;
                box-sizing: border-box;
            }
            .tip {
                color: #ef000b;
                position: absolute;
                margin-top: 4px;
                font-size: 12px;
            }
        }
    }
    .good-list-name a {
        font-size: 14px;
        cursor: pointer;
        font-weight: bold;
        color: #333;
        text-decoration: none;
        &:hover {
            text-decoration: underline;
        }
    }
}

.goods-page {
    float: right;
    margin: 30px 0 80px;
}
</style>

